﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="../Scripts/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="../Scripts/bootstrap/css/TableExp/bootstrap-table-expandable.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/bootstrap/js/jquery.min.js" type="text/javascript"></script>
    <script src="../Scripts/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    
    <script src="../Scripts/config.js" type="text/javascript"></script>
    <script src="../Comm/Gener.js" type="text/javascript"></script>
    <script src="../Scripts/QueryString.js" type="text/javascript"></script>
    <script type="text/javascript">
        var mainData = null;
        //页面启动函数.
        $(function () {
            var ensName = GetQueryString("EnsName");
            //加载JS文件
            try {
                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.src = "../../DataUser/JSLibData/" + ensName + ".js";
                var tmp = document.getElementsByTagName('script')[0];
                tmp.parentNode.insertBefore(s, tmp);
            }
            catch (err) {

            }
            InitMainTable();
        });

        //生成主表数据
        function InitMainTable() {
            var isReadonly = getQueryString("IsReadonly");
            //获得mapdtl实体的基本信息.
            var hand = new HttpHandler("BP.WF.HttpHandler.WF_CCForm");
            hand.AddUrlData();
            mainData = hand.DoMethodReturnJSON("DtlCard_Init");

            //主表数据，用于变量替换.
            var mainTable = mainData["DTDtls"]; //主表数据.
            var sys_MapDtl = mainData["Main"][0]; //从表描述.
            var sys_mapAttrs = mainData["MapAttrs"]; //从表字段.
            var mapDtls = mainData["MapDtls"]; //从表的从表集合.
            
            $('#dt_CardPanel').html(''); //清空表格数据
            //表头
            var thread = $('<thead></thead>');
            var threadTr = $('<tr></tr>');

            var columnCount = 2;
            var headTHs = [];
            var tableMinWidth = 0;
            var th = $("<th></th>");
            var rowShowModel = sys_MapDtl.EditModel;
            //有新增权限，添加按钮
            if (sys_MapDtl.IsInsert == 1&& sys_MapDtl.IsReadonly == "0" && isReadonly != "1") {
                th = $("<th><img src='../Img/Btn/Add.gif' style='cursor: pointer;' name='insertBtn' onclick='insertRow(" + rowShowModel + ")' /></th>");
            }
            th.css('width', '30px');
            threadTr.append(th);
            //生成列名
            $.each(sys_mapAttrs, function (i, mapAttrObj) {
                th = $('<th></th>');
                th.text(mapAttrObj.Name);
                th.data(mapAttrObj);
                th.css('width', mapAttrObj.UIWidth);
                th.data().colname = mapAttrObj.KeyOfEn;
                if (mapAttrObj.UIVisible == 1) {
                    columnCount++;
                    tableMinWidth += mapAttrObj.UIWidth;
                    headTHs.push(th);
                    threadTr.append(th);
                }
            });
            //添加列名行到Head
            thread.append(threadTr);
            $('#dt_CardPanel').append(thread);

            //数据行
            var tbody = $('<tbody></tbody>');
            $.each(mainTable, function (i, dataObj) {
                //主表数据
                var tbodyTr = $('<tr class="tbodyTr"></tr>');
                $.each(headTHs, function (i, th) {
                    var data = $(th).data();
                    var columName = data.colname;
                    if (data.LGType == "1" || data.LGType == "2") {
                        columName = columName + "Text";
                    }
                    var text = dataObj[columName];
                    var td = $('<td></td>');
                    td.data(dataObj);
                    td.text(text);

                    tbodyTr.append(td);
                });

                //添加操作列，删除、编辑
                var optionTD = $("<td style='width:80px;'></td>");
                if (sys_MapDtl.IsUpdate == 1) {
                    var optionEdit = $("<img src='../Img/Btn/Edit.gif' onclick='updateRow(" + dataObj.OID + ", " + rowShowModel + ")' class='updateRow' titile='修改' style='cursor:pointer;'/>");
                    optionTD.append(optionEdit);
                    optionTD.append("&nbsp;&nbsp;");       
                }
                if (sys_MapDtl.IsDelete == 1) {
                    var optionDelete = $("<img src='../Img/Btn/Delete.png' onclick='deleteRow(" + dataObj.OID + ")' class='delRow' titile='删除' style='cursor:pointer;'/>");
                    optionTD.append(optionDelete);
                }
                if(sys_MapDtl.IsReadonly == "0" && isReadonly != "1")
                    tbodyTr.append(optionTD);

                //点击行展开行后的内容
                var tbodyExpTr = $('<tr></tr>');
                var tbodyExpTd = $('<td colspan=' + columnCount + ' align="center"></td>');
                
                //加载子表
                var childTable = ChildDtls(mapDtls, tbodyExpTd, dataObj.OID);
                tbodyExpTr.append(childTable);

                //添加两条数据行，tbodyTr 父级数据，tbodyExpTr 子级内容
                tbody.append(tbodyTr);
                tbody.append(tbodyExpTr);
            });

            //小计配置规则
            if (typeof sys_MapDtl.ColAutoExp != "undefined" && sys_MapDtl.ColAutoExp != "" && mainTable.length > 0) {
                //创建统计行
                var statisticTr = addStatisticsRow(sys_MapDtl, headTHs, mainTable, false);
                if (statisticTr) {
                    //添加统计行数据
                    tbody.append(statisticTr);
                }
            }
            //表格生成完成
            $('#dt_CardPanel').append(tbody);

            try {
                //表格宽度计算
                if (sys_MapDtl.FrmW < tableMinWidth) {
                    $('#dt_CardPanel').css("width", tableMinWidth + "px");
                    $('#dt_CardPanel').css("max-width", tableMinWidth + "px");
                }

                //加载JS文件
                var s = document.createElement('script');
                s.type = 'text/javascript';
                s.src = "../Scripts/bootstrap/js/bootstrap-table-expandable.js";
                var tmp = document.getElementsByTagName('script')[0];
                tmp.parentNode.insertBefore(s, tmp);
            }
            catch (err) {

            }
        }

        //创建明细表
        function ChildDtls(mapDtls, parentTDObj, RefPK) {
            if (mapDtls.length > 0) {
                $.each(mapDtls, function (i, mapDtl) {
                    var mapAttrs = mainData[mapDtl.No];
                    var table = $('<table class="table" style="width:95%;background-color:White;"></table>');
                    //表头
                    var thread = $('<thead></thead>');
                    var threadTr = $('<tr></tr>');
                    var columnCount = 0;
                    var headTHs = [];

                    //表格列头
                    $.each(mapAttrs, function (i, mapAttrObj) {
                        var th = $('<th></th>');
                        th.text(mapAttrObj.Name);
                        th.data(mapAttrObj);
                        th.css('width', mapAttrObj.UIWidth);
                        th.data().colname = mapAttrObj.KeyOfEn;
                        if (mapAttrObj.UIVisible == 1) {
                            columnCount++;
                            headTHs.push(th);
                            threadTr.append(th);
                        }
                    });
                    thread.append(threadTr);
                    table.append(thread);

                    //表格数据
                    //获得mapdtl实体的基本信息.
                    var hand = new HttpHandler("BP.WF.HttpHandler.WF_CCForm");
                    hand.AddPara("EnsName", mapDtl.No);
                    hand.AddPara("RefPKVal", RefPK);
                    var dtlDatas = hand.DoMethodReturnJSON("DtlCard_Init_Dtl");
                    var dtlData = dtlDatas["DTDtls"];

                    //数据行
                    var tbody = $('<tbody></tbody>');
                    if (dtlData.length > 0) {
                        $.each(dtlData, function (i, dataObj) {
                            //表数据
                            var tbodyTr = $('<tr></tr>');
                            $.each(headTHs, function (i, th) {
                                var data = $(th).data();
                                var columName = data.colname;
                                if (data.LGType == "1" || data.LGType == "2") {
                                    columName = columName + "Text";
                                }
                                var text = dataObj[columName];
                                var td = $('<td></td>');
                                td.data(dataObj);
                                td.text(text);

                                tbodyTr.append(td);
                            });
                            tbody.append(tbodyTr);
                        });
                    } else {
                        var tbodyTr = $('<tr><td colspan=' + columnCount + '>无数据</td></tr>');
                        tbody.append(tbodyTr);
                    }
                    //小计配置规则
                    if (typeof mapDtl.ColAutoExp != "undefined" && mapDtl.ColAutoExp != "" && dtlData.length > 0) {
                        //创建统计行
                        var statisticTr = addStatisticsRow(mapDtl, headTHs, dtlData, true);
                        if (statisticTr) {
                            //添加统计行数据
                            tbody.append(statisticTr);
                        }
                    }
                    table.append(tbody);
                    parentTDObj.append(table);
                    parentTDObj.append("<br/>");
                });
            }
            return parentTDObj;
        }

        /// 生成统计行
        /// mapDtl: 明细表描述信息
        /// headHTs: 表格显示列头
        /// DTDtls: 明细表数据
        function addStatisticsRow(mapDtl, headHTs, DTDtls, isSub) {
            var columnExp = [];
            // 解析统计规则字符串
            $.each(mapDtl.ColAutoExp.split("@"), function (i, e) {
                if (e.indexOf(":") != -1) {
                    var sp = e.split(":");
                    columnExp.push({
                        "KeyOfEn": sp[0], // 字段
                        "exp": sp[1]		// 表达式
                    });
                }
            });

            // 统计行
            var statisticsRow = $("<tr id='dtl_Sum'></tr>");
            statisticsRow.data().customRowType = "statistics";

            if (isSub == false) {
                statisticsRow.append("<td></td>");
            }
            // 遍历表头
            $.each(headHTs, function (i, th) {
                // 根据表头的colname与待统计列的KeyOfEn对比
                var matchesColumn = $.grep(columnExp, function (val) {
                    return val.KeyOfEn == $(th).data().colname;
                });


                // 如果是统计列
                if (matchesColumn.length == 1) {
                    var keyOfEn = matchesColumn[0]["KeyOfEn"];
                    var exp = matchesColumn[0]["exp"];
                    var figureNum = 0;

                    if (exp == "Sum") {	// 和
                        // 遍历数据
                        $.each(DTDtls, function (i, dataObj) {
                            var ival = parseFloat(dataObj[keyOfEn]);
                            if (!isNaN(ival)) {
                                figureNum += ival;
                            }
                        });
                    } else if (exp == "Avg") {	// 平均数
                        var sum = 0;
                        var count = 0;
                        $.each(DTDtls, function (i, dataObj) {
                            var ival = parseFloat(dataObj[keyOfEn]);
                            if (!isNaN(ival)) {
                                sum += ival;
                                count++;
                            }
                        });
                        if (count > 0) {
                            figureNum = sum / count;
                            var strDecimal = figureNum.toString();
                            var decimalIndex = strDecimal.indexOf('.');
                            if (decimalIndex >= 0) {
                                var decimalPart = strDecimal.substring(decimalIndex + 1, strDecimal.length);
                                //小数位太多进行舍去
                                if (decimalPart.length > 4) {
                                    figureNum = Math.round(figureNum * 10000) / 10000;
                                }
                            }
                        }
                    } else if (exp == "Max") {	// 最大
                        var max = null;
                        $.each(DTDtls, function (i, dataObj) {
                            var ival = parseFloat(dataObj[keyOfEn]);
                            if (!isNaN(ival)) {
                                if (max == null) {
                                    max = ival;
                                } else if (ival > max) {
                                    max = ival;
                                }
                            }
                        });
                        figureNum = max;
                    } else if (exp == "Min") {	// 最小
                        var min = null;
                        $.each(DTDtls, function (i, dataObj) {
                            var ival = parseFloat(dataObj[keyOfEn]);
                            if (!isNaN(ival)) {
                                if (min == null) {
                                    min = ival;
                                } else if (ival < min) {
                                    min = ival;
                                }
                            }
                        });
                        figureNum = min;
                    }
                    var td = $("<td></td>");
                    td.text(figureNum);
                    statisticsRow.append(td);
                } else {
                    // 非统计列直接赋空<td></td>
                    statisticsRow.append("<td></td>");
                }
            });

            //主表需要补充一列操作列
            if (isSub == false) {
                statisticsRow.append("<td></td>");
            }
            //返回统计行
            return statisticsRow;
        }
        //插入行.
        function insertRow(EditModel) {
            //判断插入行的模式 =0行模式. 1=傻瓜表单卡片模式 2=自由表单卡片模式.
            if (EditModel != 0 && window.parent) {
                var ensName = GetQueryString("EnsName");
                var refPKVal = GetQueryString("RefPKVal");
                window.parent.DtlFrm(ensName, refPKVal, '0', EditModel, InitMainTable);
                return;
            }
        }
        //编辑行
        function updateRow(OID, EditModel) {
            if (window.parent) {
                var ensName = GetQueryString("EnsName");
                var refPKVal = GetQueryString("RefPKVal");
                window.parent.DtlFrm(ensName, refPKVal, OID, EditModel, InitMainTable);
            }
        }

        //删除行
        function deleteRow(OID) {
            var result = parent.window.confirm('确定要删除吗?');
            if (result == false)
                return;

            if (OID > 0) {
                var ensName = GetQueryString("EnsName");
                //获得mapdtl实体的基本信息.
                var hand = new HttpHandler("BP.WF.HttpHandler.WF_CCForm");

                hand.AddPara("EnsName", ensName);
                hand.AddPara("RefOID", OID);
                var dtlData = hand.DoMethodReturnJSON("Dtl_DeleteRow");
                InitMainTable();
            }
        }
    </script>
</head>
<body style="overflow:auto;">
    <table id="dt_CardPanel" class="table table-hover table-expandable" style="width:2000px;">
        <tbody>
            <tr><td style="text-align:center; color:Red;">明细表模板加载错误，请联系管理员。</td></tr>
        </tbody>
    </table>
</body>
</html>
